package cn.edu.xzit.controller;

import cn.edu.xzit.entity.Book;
import cn.edu.xzit.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping("/getAllBooks")
    public String getAllBooks() {
        List<Book> bookList = bookService.getAllBooks();
        StringBuffer stf = new StringBuffer();
        for (Book book :  bookList) {
            stf.append(book.toString());
            stf.append("<br>");
        }
        System.out.println(stf.toString());
        return stf.toString();
    }

    @GetMapping("/getBookById/{id}")
    public String getUserById(@PathVariable int id) {
        return bookService.getBookById(id).toString();
    }

    @GetMapping("/insert")
    public String  insertBook() {
        Book book=new Book();
        book.setIsbn("9787303119783");
        book.setBookName("J2EE综合案例开发");
        book.setWriter("张三");
        book.setPress("人民邮电出版社");
        book.setPrice(45.5);
        book.setRemarks("十三五规划教材");

        boolean result= bookService.insertBook(book);
        if(result){
            return "添加图书成功！";
        }else{
            return "添加图书失败！";
        }
    }

    @GetMapping(value="/getBookByIsbn/{isbn}")
    public Book getBookByIsbn(@PathVariable String isbn) {
        return bookService.getBookByIsbn(isbn);
    }


    @GetMapping("/update")
    public String updateBook(Book book) {
        book.setId(1);
        book.setIsbn("9787303119783");
        book.setBookName("J2EE综合案例开发");
        book.setWriter("李四");
        book.setPress("人民邮电出版社");
        book.setPrice(48.5);
        book.setRemarks("十三五规划教材");

        boolean result= bookService.updateBook(book);
        if(result){
            return "修改图书成功！";
        }else{
            return "修改图书失败！";
        }
    }

    @GetMapping("/deleteById/{id}")
    public String  deleteBookById(@PathVariable  int id) {
        boolean result= bookService.deleteBookById(id);
        if(result){
            return "删除图书成功！";
        }else{
            return "删除图书失败！";
        }
    }

}
